package cn.ycbjie.ycaudioplayer.newpack.linkagescroll;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;


import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.flyco.tablayout.SegmentTabLayout;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import cn.ycbjie.ycaudioplayer.R;
import cn.ycbjie.ycaudioplayer.base.BaseAppHelper;
import cn.ycbjie.ycaudioplayer.inter.OnPlayerEventListener;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.contentmode.wight.LinkMovement;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.fragment.ListFragment;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.fragment.ListFragment2;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.fragment.ListFragment3;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.fragment.TabFragment;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.utils.LogUtil;
import cn.ycbjie.ycaudioplayer.service.PlayService;
import cn.ycbjie.ycaudioplayer.ui.music.local.model.AudioMusic;


public class NestScrollingActivity extends AppCompatActivity {


    ImageView ivPlayBarCover;
    TextView tvPlayBarTitle;
    TextView tvPlayBarArtist;
    ImageView ivPlayBarPlay,iv_play_bar_list;
    ProgressBar pbPlayBar;
    private ViewPager viewPager;

    private TabLayout tabLayout;

    private NestedScrollView scrollView;

    private SwipeRefreshLayout refreshLayout;

    private AppBarLayout appBarLayout;

    private Handler handler;

    private TextView content;
    private String myid,title,picurl,created,summary;
    TextView tv_summary;

    TextView tv_updata_time;

    ImageView img_titleimg;
ImageView iv_menu;
    TextView datitle;
//    @BindView(R.id.stl_layout)
    SegmentTabLayout stlLayout;
    private String[] mStudyTitles = { "播放列表"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nest_scrolling);
        Toolbar toolbar = findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);
        Intent intent = getIntent();
        myid = intent.getStringExtra("id");
        title  = intent.getStringExtra("title");
        picurl= intent.getStringExtra("picurl");
        created= stampToDate(intent.getStringExtra("created"));
        summary = intent.getStringExtra("summary");
        findViews();
        init();
        intliser();

        String uri = picurl;
        if(uri.startsWith("https")) {
            uri = uri.substring(0, 4) + uri.substring(5, uri.length());
        }
        RequestOptions options = new RequestOptions()
                .placeholder(R.drawable.default_cover);
        Glide.with(this)
                .load(uri)
                .apply(options)

                .into(img_titleimg);
    }
    private void intliser()
    {
        ivPlayBarPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPlayService().playPause();
                onChangeImpl(getPlayService().getPlayingMusic());
            }
        });
        iv_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NestScrollingActivity.this.finish();
            }
        });
    }
    public void initPlayServiceListener() {
        if (getPlayService() == null) {
            return;
        }
        getPlayService().setOnPlayEventListener(new OnPlayerEventListener() {
            /**
             * 切换歌曲
             * 主要是切换歌曲的时候需要及时刷新界面信息
             */
            @Override
            public void onChange(AudioMusic music) {
                onChangeImpl(music);
//                if (mPlayFragment != null && mPlayFragment.isAdded()) {
//                    mPlayFragment.onChange(music);
//                }
            }

            /**
             * 继续播放
             * 主要是切换歌曲的时候需要及时刷新界面信息，比如播放暂停按钮
             */
            @Override
            public void onPlayerStart() {
                ivPlayBarPlay.setSelected(true);
//                if (mPlayFragment != null && mPlayFragment.isAdded()) {
//                    mPlayFragment.onPlayerStart();
//                }
            }

            /**
             * 暂停播放
             * 主要是切换歌曲的时候需要及时刷新界面信息，比如播放暂停按钮
             */
            @Override
            public void onPlayerPause() {
                ivPlayBarPlay.setSelected(false);
//                if (mPlayFragment != null && mPlayFragment.isAdded()) {
//                    mPlayFragment.onPlayerPause();
//                }
            }

            /**
             * 更新进度
             * 主要是播放音乐或者拖动进度条时，需要更新进度
             */
            @Override
            public void onUpdateProgress(int progress) {
                pbPlayBar.setProgress(progress);
//                if (mPlayFragment != null && mPlayFragment.isAdded()) {
//                    mPlayFragment.onUpdateProgress(progress);
//                }
            }

            @Override
            public void onBufferingUpdate(int percent) {
//                if (mPlayFragment != null && mPlayFragment.isAdded()) {
//                    mPlayFragment.onBufferingUpdate(percent);
//                }
            }

            /**
             * 更新定时停止播放时间
             */
            @Override
            public void onTimer(long remain) {

            }
        });
    }
    public void onChangeImpl(AudioMusic music) {
        if (music == null) {
            return;
        }
//        Bitmap cover = CoverLoader.getInstance().loadThumbnail(music);

        RequestOptions options = new RequestOptions()
                .placeholder(R.drawable.default_cover);
        Glide.with(this)
                .load(music.getCoverPath())
                .apply(options)
                .into(ivPlayBarCover);

/*圆图
        Glide.with(this).load(music.getCoverPath()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(ivPlayBarCover);
*/




//        ivPlayBarCover.setImageBitmap(cover);
        tvPlayBarTitle.setText(music.getTitle());
        tvPlayBarArtist.setText(music.getArtist());
        boolean isplaying = getPlayService().isPlaying();
        boolean ispre = getPlayService().isPreparing();
        boolean isdef = getPlayService().isDefault();

        ivPlayBarPlay.setSelected(getPlayService().isPlaying() || getPlayService().isPreparing());
        //更新进度条
        pbPlayBar.setMax((int) music.getDuration());
        pbPlayBar.setProgress((int) getPlayService().getCurrentPosition());

    }

    public PlayService getPlayService() {
        PlayService playService = BaseAppHelper.get().getPlayService();
        if (playService == null) {
            throw new NullPointerException("play service is null");
        }
        return playService;
    }
    private String stampToDate(String GMT) {
        String createTime = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
//        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(GMT);
            createTime = sdf2.format(date);
//            holder.tvProbationTime.setText("申请于" + createTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return createTime;
    }
    private void findViews() {
        View viewhead = findViewById(R.id.in_header);
        stlLayout = (SegmentTabLayout)viewhead.findViewById(R.id.stl_layout);
        iv_menu = (ImageView)findViewById(R.id.iv_menu);
        viewPager = findViewById(R.id.data_pager);
        tabLayout = findViewById(R.id.tab_layout);
        scrollView = findViewById(R.id.nested_scroll_view);
        refreshLayout = findViewById(R.id.refresh_layout);
        appBarLayout = findViewById(R.id.app_bar);
        content = findViewById(R.id.textView_content);

        tv_summary= findViewById(R.id.tv_summary);

        tv_updata_time= findViewById(R.id.tv_updata_time);

        img_titleimg=  findViewById(R.id.img_titleimg);

        datitle=  findViewById(R.id.tv_datitle);
        View view = findViewById(R.id.in_playbar);
        ivPlayBarCover =(ImageView)view.findViewById(R.id.iv_play_bar_cover);
        tvPlayBarTitle = (TextView)view.findViewById(R.id.tv_play_bar_title);
        tvPlayBarArtist = (TextView)view.findViewById(R.id.tv_play_bar_artist);
        ivPlayBarPlay = (ImageView)view.findViewById(R.id.iv_play_bar_play);
        pbPlayBar= (ProgressBar)view.findViewById(R.id.pb_play_bar);
        iv_play_bar_list=(ImageView)view.findViewById(R.id.iv_play_bar_list);

//        tabLayout.post(new Runnable() {
//            @Override
//            public void run() {
//                tabLayout, 40, 40);
//            }
//        });

        setTabLine(tabLayout,900,900);

//        tabLayout = (TabLayout) mView.findViewById(R.id.trade_tl);

        //修改tablayout的下划线宽度
//        tabLayout.post(new Runnable() {
//            @Override
//            //我们在这里对TabLayout的宽度进行修改。。数值越大表示宽度越小。
//            public void run()
//            {
//
//                tabLayout, 40, 40);
//            }
//        });

    }

    public void setTabLine(TabLayout tab,int left,int right){
        try {
            Class<?> tablayout = tab.getClass();
            Field tabStrip = tablayout.getDeclaredField("mTabStrip");
            tabStrip.setAccessible(true);
            LinearLayout ll_tab= (LinearLayout) tabStrip.get(tabLayout);
            for (int i = 0; i < ll_tab.getChildCount(); i++) {
                View child = ll_tab.getChildAt(i);
                child.setPadding(0,0,0,0);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT,1);
                //修改两个tab的间距

                params.setMarginStart(dip2px(this,left));
                params.setMarginEnd(dip2px(this,right));
                child.setLayoutParams(params);
                child.invalidate();
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            Log.e("bianju",e.toString());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            Log.e("bianju",e.toString());
        }
    }

    public static int dip2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    public void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("slidingTabIndicator");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }


    /**
     *
     */
    private void init() {

        stlLayout.setTabData(mStudyTitles);
//        stlLayout.setOnTabSelectListener(new OnTabSelectListener() {
//            @Override
//            public void onTabSelect(int position) {
//                vpContent.setCurrentItem(position);
//            }
//
//            @Override
//            public void onTabReselect(int position) {
//            }
//        });

        datitle.setText(title);
        tv_updata_time.setText(created+"更新");
        tv_summary.setText(summary);
        handler = new Handler(getMainLooper());
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (!refreshLayout.isRefreshing()) {
                    refreshLayout.setEnabled(verticalOffset == 0);
                }
                LogUtil.e("verticalOffset=" + verticalOffset);
            }
        });
        viewPager.setAdapter(new TabAdapter(getSupportFragmentManager()));
        viewPager.setOffscreenPageLimit(3);
        tabLayout.setupWithViewPager(viewPager);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(false);
                    }
                }, 500);
            }
        });

        // fix 文本有点击事件会拦截底部事件
        content.setOnTouchListener(LinkMovement.getInstance());
    }

    private class TabAdapter extends FragmentPagerAdapter {

        private List<Fragment> fragmentList = new ArrayList<>();
        private List<String> tabList = new ArrayList<>();
        public TabAdapter(FragmentManager fm) {
            super(fm);
            TabFragment listFragment1 = new TabFragment(myid,NestScrollingActivity.this,picurl);
            TabFragment listFragment2 = new TabFragment(myid,NestScrollingActivity.this,picurl);
            ListFragment3 listFragment3 = new ListFragment3(myid);
//            TabFragment tabFragment = new TabFragment();
            fragmentList.add(listFragment1);
            tabList.add("详情");
            fragmentList.add(listFragment2);
            tabList.add("列表");
            fragmentList.add(listFragment3);
            tabList.add("待定");
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
//            return  new TabFragment();
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabList.get(position);
        }
    }

}
